package com.huaxin.hxcloud.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.huaxin.common.AppManager;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.AppVersionDTO;
import com.huaxin.common.cache.DiskCache;
import com.huaxin.common.tools.AppOperator;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.HxUtils;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.hxcloud.BuildConfig;
import com.huaxin.hxcloud.R;

import java.io.IOException;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/11/16.
 */
public class AboutActivity extends BaseActivity {


    @BindView(R.id.more)
    ImageView more;
    @BindView(R.id.tv_unread)
    TextView tvUnread;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.check_update_layout)
    LinearLayout checkUpdateLayout;
    @BindView(R.id.call_number)
    TextView callNumber;
    @BindView(R.id.call_layout)
    LinearLayout callLayout;
    @BindView(R.id.tv_company_profile)
    TextView tvCompanyProfile;
    private String updateUrl;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_about;
    }

    @Override
    public void initView() {
        super.initView();
        setSupportActionBar(toolbar);
        toolbar.setTitle("治水");
        tvVersion.setText("当前版本 " + BuildConfig.VERSION_NAME);
        callNumber.setText(Constants.CUSTOMER_SERVICE);
    }


    @Override
    public void initData() {

    }

    @OnClick({R.id.check_update_layout, R.id.call_layout})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.check_update_layout:
                ApiCheckUpdate();

                break;
            case R.id.call_layout:
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) !=
                        PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + Constants
                            .CUSTOMER_SERVICE));
                    startActivity(intent);
                    return;
                }
                break;
            default:
                break;
        }
    }

    private void ApiCheckUpdate() {
        Call<AppVersionDTO> call = RequestHelper.getRequestApi().checkUpdate(HxUtils.getVersionName(this) , 0);
        call.enqueue(new Callback<AppVersionDTO>() {
            @Override
            public void onResponse(Call<AppVersionDTO> call, Response<AppVersionDTO> response) {
                AppVersionDTO appVersionDTO = response.body();
                if (response.isSuccessful() && appVersionDTO != null) {
                    if (appVersionDTO.isSuccessful()) {
                        updateUrl = appVersionDTO.getFileName();
//                        String version = appVersionDTO.getVersion();
//                        if (Float.valueOf(version) > Float.valueOf(com.huaxin.common.BuildConfig
//                                .VERSION_CODE)) {
//                            checkUpdate();
                            showUpdateDialog(AppManager.getAppManager().currentActivity(),
                                    updateUrl);
//                        } else {
//                            ToastUtil.showToast("已经是最新版本");
//                        }

                    }else{
                        ToastUtil.showToast("已经是最新版本");
                    }
                }
            }


            @Override
            public void onFailure(Call<AppVersionDTO> call, Throwable t) {
                ToastUtil.showToast("网络故障");
            }
        });

    }



    /*
       *
       * 弹出对话框通知用户更新程序
       */
    public static void showUpdateDialog(final Context context, final String url) {
        if (context == null) {
            return;
        }
        Dialog dialog = DialogUtil.getConfirmDialog(context, "检测到新版本，是否升级",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        ToastUtil.showToast("后台开始下载,请您稍等");
                        downLoadApk(context, url);
                    }
                },
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
//                        ToastUtil.showToast("您可以到设置界面手动更新");
//                        downLoadApk(context, url);
                    }
                }).create();
        dialog.show();
    }

    private static void downLoadApk(final Context context, final String url) {
        AppOperator.runOnThread(new Runnable() {
            @Override
            public void run() {
                if(downLoadApp(url))  {
                    installApk(context);
                }else{
                    ToastUtil.showToast("更新包下载失败");
                }

            }
        });
    }


    private static boolean downLoadApp(String url){
        boolean ret = false;
        Call<ResponseBody> call = RequestHelper.getRequestApi().downloadFile(url);
        Response<ResponseBody> response = null;
        try {
            response = call.execute();
            if(response.isSuccessful()){
                ret =  DiskCache.putInputStream(Constants.APP_NAME, response.body().byteStream());
            }
        } catch (IOException e) {
            e.printStackTrace();
            ret =  false;
        }
        return ret;
    }

    // 安装apk
    private static void installApk(final Context context) {
        Intent intent = new Intent();
        // 执行动作
        intent.setAction(Intent.ACTION_VIEW);
        // 执行的数据类型
        intent.setDataAndType(Uri.fromFile(DiskCache.getFile(Constants.APP_NAME)),
                "application/vnd.android.package-archive");
        context.startActivity(intent);
    }
}
